package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.SysInterface;
import com.example.tongyao.system.entity.SysUser;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.system.service.ISysInterfaceService;
import com.example.tongyao.utils.*;
import com.example.tongyao.utils.token.UserUtils;
import com.example.tongyao.utils.tongyao.TyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单接口表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-18
 */
@RestController
@Api(tags = "系统_菜单接口前端控制器")
@RequestMapping("/system/sys-interface")
public class SysInterfaceController extends SuperController{

    @Resource
    private ISysInterfaceService iSysInterfaceService;

    /**
     * 分页查询所有菜单接口
     * @return
     */
    @ApiOperation(
            value = "查询菜单接口",
            notes = "分页查询所有菜单接口",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceName",value = "菜单接口名称"),
            @ApiImplicitParam(name = "menuId",value = "菜单编号"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "si.create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/page" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page(
            @RequestParam(required = false) String interfaceName,
            @RequestParam(required = false) String menuId,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "si.create_time") String sortBy,
            @RequestParam(defaultValue = "asc") String order) {

        PageUtil<SysInterface> page = new PageUtil<>(pageNo,pageSize,sortBy,order);
        Map<String, Object> params = TyUtils.toObjectMap(page);
        params.put("interfaceName",interfaceName);
        params.put("menuId",menuId);


        List<SysInterface> list = iSysInterfaceService.interfacePage(params);
        page.setPage(list,list.size(),pageNo);
        return DataResult.setSuccess(page);
    }

    @ApiOperation(
            value = "增加菜单接口",
            notes = "增加一个菜单接口",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysInterface sysInterface) {

        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysInterface.setInterfaceEnabled(true);
        sysInterface.setDelFlag(1);

        sysInterface.setCreateBy(user.getUserId());
        sysInterface.setCreateTime(DateUtils.getDateTime());

        reuslt = iSysInterfaceService.save(sysInterface);
        if(!reuslt){
            throw new RuntimeException(SystemMessage.sysInterface+SystemMessage.add+SystemMessage.fail+SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "编辑菜单接口",
            notes = "编辑一个菜单接口，需根据interfaceId字段。",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody SysInterface sysInterface){

        SysUser user = (SysUser) UserUtils.getUserInfo();

        if(StringUtils.isBlank(sysInterface.getInterfaceId())){
            throw new RuntimeException("菜单接口编号不能为空！");
        }

        LambdaUpdateWrapper<SysInterface> sysInterfaceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        if(StringUtils.isNotBlank(sysInterface.getInterfaceName())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getInterfaceName,sysInterface.getInterfaceName());
        }
        if(StringUtils.isNotBlank(sysInterface.getInterfaceDesc())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getInterfaceDesc,sysInterface.getInterfaceDesc());
        }
        if(StringUtils.isNotBlank(sysInterface.getInterfaceAddress())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getInterfaceAddress,sysInterface.getInterfaceAddress());
        }
        if(StringUtils.isNotNull(sysInterface.getSort())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getSort,sysInterface.getSort());
        }
        if(StringUtils.isNotNull(sysInterface.getMenuId())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getMenuId,sysInterface.getMenuId());
        }
        if(StringUtils.isNotNull(sysInterface.getInterfaceType())){
            sysInterfaceLambdaUpdateWrapper.set(SysInterface::getInterfaceType,sysInterface.getInterfaceType());
        }

        sysInterfaceLambdaUpdateWrapper.set(SysInterface::getModifyBy,user.getUserId());
        sysInterfaceLambdaUpdateWrapper.set(SysInterface::getModifyTime,DateUtils.getDateTime());

        sysInterfaceLambdaUpdateWrapper.eq(SysInterface::getInterfaceId,sysInterface.getInterfaceId());

        reuslt = iSysInterfaceService.update(sysInterfaceLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.sysInterface+
                            SystemMessage.update+
                            SystemMessage.fail+
                            SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除菜单接口",
            notes = "删除一个或多个菜单接口",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId",value = "菜单接口编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String interfaceId){

        List interfaceIds = Arrays.asList(interfaceId.split(","));
        for (Object interfaceID: interfaceIds) {

            //删除字典
            LambdaUpdateWrapper<SysInterface> sysInterfaceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            sysInterfaceLambdaUpdateWrapper
                    .set(SysInterface::getDelFlag,"0")
                    .eq(SysInterface::getInterfaceId,interfaceID);
            reuslt = iSysInterfaceService.update(sysInterfaceLambdaUpdateWrapper);
            if(!reuslt){
                throw new RuntimeException(
                        SystemMessage.sysInterface+
                                SystemMessage.delete+
                                SystemMessage.fail+
                                SystemMessage.a
                );
            }

        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "更改状态",
            notes = "更改菜单接口编号的启用禁用状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "interfaceId",value = "菜单接口编号",required = true),
            @ApiImplicitParam(name = "state",value = "菜单接口状态（true为启用，false为禁用）",required = true)
    })
    @PutMapping(value = "/changeState" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult changeState(
            @RequestParam String interfaceId,
            @RequestParam boolean state
    ){

        LambdaUpdateWrapper<SysInterface> sysInterfaceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysInterfaceLambdaUpdateWrapper
                .set(SysInterface::isInterfaceEnabled,state)
                .eq(SysInterface::getInterfaceId,interfaceId);
        reuslt = iSysInterfaceService.update(sysInterfaceLambdaUpdateWrapper);

        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.sysInterface +
                            SystemMessage.state+
                            SystemMessage.update +
                            SystemMessage.fail +
                            SystemMessage.a
            );
        }

        return DataResult.setSuccess(null);
    }
}
